<template>
  <!--display: flex;等价于父级overflow: hidden;子级float: left;-->
  <div style="display: flex;">
    <!--左侧菜单栏-->
    <div :style="{width: (isCollapse ? '64px': '208px')}">
      <!--unique-opened:同一时刻只展开一个菜单项-->
      <el-menu id="left-menu"
               class="left-menu"
               background-color="#3C82F5"
               text-color="#fff"
               unique-opened
               :collapse="isCollapse"
               :collapse-transition="false"
               :default-active="activeItem"
               active-text-color="yellow"
               @select="selectMenu"
               router
      >
        <el-row style="padding-top: 10px;">
          <el-col :span="2"></el-col>
          <el-col :span="7" style="padding-left: 7px;">
            <el-avatar class="avatar-img" src="/imgs/admin/logo.png"></el-avatar>
          </el-col>
          <!-- 折叠按钮 -->
          <el-col :span="isCollapse ? 0 : 13">
            <router-link class="logo-text" @click="activateUserMenu" to="/">智慧车辆</router-link>
          </el-col>
        </el-row>
        <el-sub-menu index="1">
          <template #title>
            <el-icon style="font-size: 21px;">
              <User/>
            </el-icon>
            <span>用户管理</span>
          </template>
          <el-menu-item index="/user">用户列表</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="2">
          <template #title>
            <el-icon style="font-size: 21px;">
              <Van/>
            </el-icon>
            <span>车辆管理</span>
          </template>
          <el-menu-item index="/vehicle">基本信息</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="3">
          <template #title>
            <el-icon style="font-size: 21px;">
              <Location/>
            </el-icon>
            <span>电子围栏</span>
          </template>
          <el-menu-item index="/geofence">围栏管理</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="4">
          <template #title>
            <el-icon style="font-size: 21px;">
              <Place/>
            </el-icon>
            <span>调度管理</span>
          </template>
          <el-menu-item index="/application">申请列表</el-menu-item>
          <el-menu-item index="/audit">调度审核</el-menu-item>
          <el-menu-item index="/distribute">车辆分配</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="5">
          <template #title>
            <el-icon style="font-size: 21px;">
              <MessageBox/>
            </el-icon>
            <span>数据字典</span>
          </template>
          <el-menu-item index="/dict">字典管理</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </div>
    <!--右侧主体内容(-前后必须要有空格!!!)-->
    <div :style="{width:(isCollapse ? 'calc(100% - 64px)': 'calc(100% - 208px)')}">
      <!--右侧顶部条:折叠按钮+用户名-->
      <el-header class="header">
        <el-row :gutter="10">
          <el-col :span="18">
            <el-icon style="font-size: 20px;" @click="changeCollapse">
              <Expand/>
            </el-icon>
          </el-col>
          <!--子绝父相,将菜单栏右侧的用户名右对齐-->
          <el-col :span="6" style="position: relative;">
            <el-dropdown
                style="position: absolute;right: 20px;"
                trigger="click"
            >
              <span class="username">
                {{ user.username }}
                <el-icon>
                  <arrow-down/>
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openLogoutConfirmBox">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>
        <!--面包屑导航-->
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item v-for="item in breadcrumb">{{ item }}</el-breadcrumb-item>
        </el-breadcrumb>
      </el-header>
      <!--右侧主体内容-->
      <el-main class="right-main">
        <!--<router-view/>表示该区域是可变内容-->
        <router-view/>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import {ref, nextTick, onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

// 定义菜单栏是否折叠, 默认不折叠
const isCollapse = ref(false);
// 是否激活折叠
const changeCollapse = () => {
  isCollapse.value = !isCollapse.value;
}

// 通过 ref 定义 activeItem，用于动态设置默认激活项
const activeItem = ref(sessionStorage.getItem('activeMenu') || '/user');
// 定义方法，激活用户列表菜单子项
const activateUserMenu = () => {
  try {
    nextTick(() => {
      let index = '/user';
      breadcrumb.value = map[index];
      // 解决面包屑刷新丢失问题:存到sessionStorage中
      sessionStorage.setItem('breadcrumb', JSON.stringify(breadcrumb.value));
      activeItem.value = index;
      sessionStorage.setItem('activeMenu', activeItem.value);
    });
  } catch (error) {
    console.error('Error in activateUserMenu:', error);
  }
};
// 页面刷新或组件加载时执行特定方法
onMounted(() => {
  try {
    const savedMenu = sessionStorage.getItem('activeMenu');
    if (savedMenu) {
      activeItem.value = savedMenu;
    } else {
      activateUserMenu();
    }
  } catch (error) {
    console.error('Error in onMounted:', error);
  }
});
// 获取当前登录用户
const user = ref(getCurrentUser());

// 定义数组用来保存面包屑导航显示的值
const breadcrumb = ref(JSON.parse(sessionStorage.getItem('breadcrumb')) || ['用户管理', '用户列表']);
// 维护面包屑导航与菜单项index的对应关系
let map = {
  '/user': ['用户管理', '用户列表'],
  '/vehicle': ['车辆管理', '基本信息'],
  '/geofence': ['电子围栏', '围栏管理'],
  '/application': ['调度申请', '申请列表'],
  '/audit': ['调度审核', '调度审核'],
  '/distribute': ['车辆分配', '车辆分配'],
  '/dict': ['数据字典', '字典管理']
};
// 只要选择菜单项,就切换面包屑的值
const selectMenu = (index) => {
  try {
    breadcrumb.value = map[index];
    // 解决面包屑刷新丢失问题:存到sessionStorage中
    sessionStorage.setItem('breadcrumb', JSON.stringify(breadcrumb.value));
    // 激活菜单项,并将激活菜单记录到sessionStorage中
    activeItem.value = index;
    sessionStorage.setItem('activeMenu', index);
  } catch (error) {
    console.error('Error in selectMenu:', error);
  }
}

// 退出登录功能
const openLogoutConfirmBox = () => {
  ElMessageBox.confirm(
      '确认要退出登录吗?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 1.删除sessionStorage的user
        sessionStorage.removeItem('user');
        // 2.删除sessionStorage的breadcrumb
        sessionStorage.removeItem('breadcrumb');
        // 3.清空user
        user.value = {};
        // 4.弹窗提示
        // ElMessage({
        //   type: 'success',
        //   message: '已退出登录',
        // })
        // 5.跳转到登录页面
        setTimeout(()=>{
          window.location.href = '/login';
        },300);
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '操作取消',
        })
      })
}
</script>

<style scoped>
.left-menu {
  width: 100%;
  height: 100vh;
}

.avatar-img {
  width: 35px;
  height: 35px;
}

.logo-text {
  text-decoration: none;
  color: #fff;
  font-weight: bold;
  position: relative;
  font-size: 18px;
  top: 6px;
  left: 2px;
}

.header {
  padding-top: 22px;
  height: 10vh;
  background-color: #fff;
}

.username {
  font-size: 19px;
  font-weight: bold;
}

.breadcrumb {
  position: relative;
  top: 20px;
}

.right-main {
  padding: 0;
  height: 90vh;
  overflow: auto;
}
</style>